﻿using MongoDB.Bson;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace HBase {
    /**
   *┌────────────────────────────────────────────────┐
   *│　描    述：MyReflectionUtil                                                    
   *│　作    者：sgj                                              
   *│　版    本：1.0                                              
   *│　创建时间：2021/11/3 13:51:01                        
   *└────────────────────────────────────────────────┘
   **/
    public class MyReflectionUtil {

        static public void setFValue(Object obj ,String name ,Object value) {
            Type t = obj.GetType();
            FieldInfo info = t.GetField(name);
            info.SetValue(obj ,value);
        }

        static public Object getFValue(Object obj ,String name) {
            Type t = obj.GetType();
            FieldInfo info = t.GetField(name);
            return info.GetValue(obj);
        }
        static public Object getPValue(Object obj, String name) {
            Type t = obj.GetType();
            PropertyInfo info = t.GetProperty(name);

            return info.GetValue(obj);
        }


        public static PropertyInfo[] GetPropertyInfos(Type type) {
        
            return type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy);
        }

        public static void AutoMappingGS<S, T>(S s ,T t ) {
            // get source PropertyInfos
            PropertyInfo[] pps = GetPropertyInfos(s.GetType());
            // get target type
            Type target = t.GetType();

            foreach( var pp in pps ) {
                PropertyInfo targetPP = target.GetProperty(pp.Name);
                object value = pp.GetValue(s ,null);

                if( targetPP != null && value != null ) {
                    targetPP.SetValue(t ,value ,null);
                }
            }

        }

        public static void copy<S, T>(S s, T t, params string[] p) {
            // get source PropertyInfos
            PropertyInfo[] pps = GetPropertyInfos(s.GetType());
            // get target type
            Type target = t.GetType();

            foreach (var pp in pps) {
                String pN=pp.Name;
                if (!p.Contains(pN)) {
                    continue;
                }
                PropertyInfo targetPP = target.GetProperty(pp.Name);
                object value = pp.GetValue(s, null);

                if (targetPP != null && value != null) {
                    targetPP.SetValue(t, value, null);
                }
            }

        }
    }
}
